# -*- coding: utf-8 -*-
#coding=utf-8

import web
import os
import config
import hashlib
from action.admin.base import adminAction
from model.user import user
from model.album import album
from model.image import image

'''
Admin controller: producing user administration views.
'''
class refererAction(adminAction):
    def __init__(self, name = '会员管理'):
        adminAction.__init__(self, name)


    def GET(self, name):
        if name == 'list':
            return self.list()
        elif name == 'delete':
            return self.delete()
        elif name == 'listForBatchDel':
            return self.listForBatchDel()
        elif name == 'add':
            return self.add()
        elif name == 'edit':
            return self.edit()
        else:
            return self.notFound()

    def POST(self, name):
        if name == 'save':
            return self.save()
        elif name == 'modify':
            return self.modify()
        elif name == 'deleteBatch':
            return self.deleteBatch()
        else:
            return self.notFound()

    def list(self):
        inputParams = self.getInput()
        page = int(inputParams['page']) if inputParams.has_key('page') else 1
        count = config.COUNT_PER_PAGE
        offset= (page-1)*count if page > 0 else 0
   
        condition = {}
        userObj = user()
        listData = userObj.getOne('COUNT(*) AS `total`',condition)
        totalCount = listData['total']
        userList = userObj.getList('*', condition, 'email asc', str(offset) + ',' + str(count))
        pageString = self.getPageStr('/admin/user/list', page, count, totalCount)
        self.privData['USER_LIST'] = userList
        self.privData['PAGE_STRING'] = pageString
        return self.display('userList')

    def listForBatchDel(self):
        inputParams = self.getInput()
        page = int(inputParams['page']) if inputParams.has_key('page') else 1
        count = config.COUNT_PER_PAGE
        offset= (page-1)*count if page > 0 else 0
   
        condition = {}
        userObj = user()
        listData = userObj.getOne('COUNT(*) AS `total`',condition)
        totalCount = listData['total']
        userList = userObj.getList('*', condition, 'email asc', str(offset) + ',' + str(count))
        pageString = self.getPageStr('/admin/user/list', page, count, totalCount)
        self.privData['USER_LIST'] = userList
        self.privData['PAGE_STRING'] = pageString
        return self.display('userBatchDel')

    def delete(self):
        inputParams = self.getInput()

        try:
            condition={'email': inputParams['email']}
            user().delete(condition)
        except Exception, e:
            return self.success(msg='会员删除失败: %s' % e, url=self.makeUrl('/admin/user/list'))

        return self.success(msg='会员删除成功', url=self.makeUrl('/admin/user/list'))

    def deleteBatch(self):
        inputParams = self.getInput()
        try:
            condition = ' id IN (' + inputParams['delitems'] +')'
            user().delete(condition)
        except Exception, e:
            return self.error(msg='对象删除失败: %s' % e, url=self.makeUrl('/admin/user/list'))

        return self.success(msg='对象删除成功', url=self.makeUrl('/admin/user/list'))


    def add(self):
        condition = {}
        albumList = album().getList('*', condition)
        self.privData['ALBUM_LIST'] = {}
        for item in albumList:
            self.privData['ALBUM_LIST'][item['id']] = item['name']

        self.privData['IMG_ALBUM_LIST'] = {}
        for i in albumList:
            self.privData['IMG_ALBUM_LIST'][i['id']] = {};
            imageList = image().getList('*',{'album': i['id']}, orders="id asc")
            for img in imageList:
                self.privData['IMG_ALBUM_LIST'][i['id']][img['id']] = img['desc']

        self.privData['CURRENT_ALBUM'] = 1
        self.privData['CURRENT_IMG'] = 1
        self.privData['SUBMIT_NAME'] = "avatur"

        return self.display('userAdd')
    
    def modify(self):
        userInput= self.getInput()
        password = hashlib.md5(userInput['passwd']).hexdigest()
        data={
            'passwd'    :   password,
            'nickname'  :   userInput['nickname'],
            'name'      :   userInput['name'],
            'phoneno'   :   userInput['phoneno'],
            'address'   :   userInput['address'],
            'gender'    :   int(userInput['gender']),
            'avatur'    :   int(userInput['avatur']),
            'rank'      :   int(userInput['rank']),
        }

        try:
            condition={'email': userInput['email']}
            user().update(data, condition)
        except Exception, e:
            return self.error(msg = '会员修改失败: %s' % e, url=self.makeUrl('/admin/user/list'))

        return self.success('会员修改成功', url=self.makeUrl('/admin/user/list'))

    def edit(self):
        inputParams = self.getInput()

        condition={'email': inputParams['email']}
        userObj = user().getOne('*', condition)
        if not userObj:
            return self.error(msg = '该会员不存在', url=self.makeUrl('/admin/user/list'))

        self.privData['USER_INFO'] = userObj

        condition = {}
        albumList = album().getList('*', condition)
        self.privData['ALBUM_LIST'] = {}
        for item in albumList:
            self.privData['ALBUM_LIST'][item['id']] = item['name']

        self.privData['IMG_ALBUM_LIST'] = {}
        for i in albumList:
            self.privData['IMG_ALBUM_LIST'][i['id']] = {};
            imageList = image().getList('*',{'album': i['id']}, orders="id asc")
            for img in imageList:
                self.privData['IMG_ALBUM_LIST'][i['id']][img['id']] = img['desc'] 

        self.privData['CURRENT_ALBUM'] = 1
        self.privData['CURRENT_IMG'] = userObj["avatur"]
        self.privData['SUBMIT_NAME'] = "avatur"

        return self.display('userEdit')


    def save(self):
        userInput = self.getInput()  
        password = hashlib.md5(userInput['passwd']).hexdigest()
        data = {
            'email'     :   userInput['email'],
            'passwd'    :   password,
            'nickname'  :   userInput['nickname'],
            'name'      :   userInput['name'],
            'phoneno'   :   userInput['phoneno'],
            'address'   :   userInput['address'],
            'gender'    :   int(userInput['gender']),
            'avatur'    :   int(userInput['avatur']),
            'rank'      :   int(userInput['rank']),
        }

        try:
            user().insert(data)
        except Exception, e:
            return self.error(msg = '会员保存失败: %s' % e, url=self.makeUrl('/admin/user/list'))

        return self.success('会员保存成功', url=self.makeUrl('/admin/user/list'))
